package cn.auction.web;

import cn.auction.biz.AuctionService;
import cn.auction.biz.impl.AuctionServiceImpl;
import cn.auction.entity.Auction;
import cn.auction.entity.AuctionRecord;
import cn.auction.entity.AuctionUser;
import cn.auction.util.Page;
import cn.auction.util.Tool;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AuctionCon {
    public AuctionCon() {
    }
    //发布拍卖信息
    public String addAuction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String uploadFileName = "";  //上转的文件名
            String fieldName = "";
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);//用于判断是普通表单，还是带文件上传的表单
            String uploadFilePath = request.getServletContext().getRealPath("/upload/");//创建文件路径
            File fullFile = null;
            String fileType = null; //文件类型
            Auction auction = new Auction();
            if (isMultipart) {
                //创建DiskFileItemFactory对象
                FileItemFactory factory = new DiskFileItemFactory();
                //创建servletFileUpLoad对象将请求表单中的每一项转换为FileItem对象
                ServletFileUpload upload = new ServletFileUpload(factory);
                //把前端请求封装成一个FileItem对象,需要从servletFileUpLoad中获取
                List<FileItem> items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                while(iter.hasNext()) {
                    FileItem item = (FileItem)iter.next();
                    String value;
                    if (item.isFormField()) {////判断上传文件是带文件的表单还是普通的表单
                        fieldName = item.getFieldName();//返回表单标签的name属性的值
                        value = item.getString("UTF-8"); //设置name属性的字符集
                        if (fieldName.equals("auctionName")) {
                            auction.setAuctionName(value);
                        }
                        if (fieldName.equals("startPrice")) {
                            auction.setAuctionStartPrice(new Double(value));
                        }

                        if (fieldName.equals("upset")) {
                            auction.setAuctionUpset(new Double(value));
                        }

                        if (fieldName.equals("startTime")) {
                            auction.setAuctionStartTime(Tool.strToDate(value, "yyyy-MM-dd HH:mm:ss"));
                        }

                        if (fieldName.equals("endTime")) {
                            auction.setAuctionEndTime(Tool.strToDate(value, "yyyy-MM-dd HH:mm:ss"));
                        }

                        if (fieldName.equals("desc")) {
                            auction.setAuctionDesc(value);
                        }
                    } else {//带文件的表单
                        value = item.getName();//获取上传的文件名
                        if (value != null && !value.equals("")) {
                            fullFile = new File(value);//创建File对象
                            File saveFile = new File(uploadFilePath, fullFile.getName());
                            item.write(saveFile);//写入
                            uploadFileName = fullFile.getName();
                            fileType = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                            System.out.println("上传成功后的文件名是：" + uploadFileName);
                        }
                    }
                }
            }
            AuctionService biz = new AuctionServiceImpl();
            auction.setAuctionPic("upload/" + uploadFileName);
            auction.setAuctionPicType(fileType);
            biz.add(auction);
            return "redirect:/do/auction/auctionList";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            return "/error.jsp";
        }
    }
    //添加竞拍信息
    public String addAuctionRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            AuctionService biz = new AuctionServiceImpl();
            AuctionRecord record = new AuctionRecord();
            record.setAuctionId(new Long(request.getParameter("auctionId")));
            record.setAuctionPrice(new Double(request.getParameter("auctionPrice")));
            record.setUserId(((AuctionUser)request.getSession().getAttribute("user")).getUserId());
            record.setAuctionTime(new Date());
            biz.bid(record);
            return "redirect:/do/auction/auctionDetail?auctionId=" + request.getParameter("auctionId");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            return "/error.jsp";
        }
    }

    public String showAuctionDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            AuctionService biz = new AuctionServiceImpl();
            Auction auction = biz.findById(new Long(request.getParameter("auctionId")));
            request.setAttribute("auction", auction);
            return "/auctionDetail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            return "/error.jsp";
        }
    }

    public String showAuctionList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            AuctionService auctionService=new AuctionServiceImpl();
            Auction auction = new Auction();
            int index=1;
            if (request.getParameter("pageIndex") != null) {
                index = new Integer(request.getParameter("pageIndex"));
            }
            if (request.getParameter("auctionName") != null && !"".equals(request.getParameter("auctionName"))){
                auction.setAuctionName(request.getParameter("auctionName"));
            }
            if (request.getParameter("auctionDesc") != null && !"".equals(request.getParameter("auctionDesc"))) {
                auction.setAuctionDesc(request.getParameter("auctionDesc"));
            }

            if (request.getParameter("auctionStartTime") != null && !"".equals(request.getParameter("auctionStartTime"))) {
                auction.setAuctionStartTime(Tool.strToDate(request.getParameter("auctionStartTime"), "yyyy-MM-dd HH:mm:ss"));
            }

            if (request.getParameter("auctionEndTime") != null && !"".equals(request.getParameter("auctionEndTime"))) {
                auction.setAuctionEndTime(Tool.strToDate(request.getParameter("auctionEndTime"), "yyyy-MM-dd HH:mm:ss"));
            }

            if (request.getParameter("auctionStartPrice") != null && !"".equals(request.getParameter("auctionStartPrice"))) {
                auction.setAuctionStartPrice(new Double(request.getParameter("auctionStartPrice")));
            }
            Page<Auction> auctionPage = auctionService.find(auction, index);
            request.setAttribute("auctionPageInfo", auctionPage);
            return "/auctionList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            return "/error.jsp";
        }
    }

    public String showAuctionResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            AuctionUser user = (AuctionUser)request.getSession().getAttribute("user");
            AuctionService auctionService = new AuctionServiceImpl();
            Map<String, List> map = auctionService.find(user);
            request.setAttribute("map", map);
            return "/auctionResult.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            return "/error.jsp";
        }
    }
}
